package com.plugin.manage.controller;

import com.plugin.manage.common.RespObj;
import com.plugin.manage.pojo.vo.ElderAssessmentVO;
import com.plugin.manage.pojo.vo.ElderCheckinDetailVO;
import com.plugin.manage.service.ICheckinService;
import com.plugin.manage.service.IElderAssessmentService;
import com.plugin.manage.service.IElderService;
import com.plugin.manage.service.IRoomService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

/**
 * 入住管理控制器
 *
 * @author mark
 * @date 2025-07-31
 */
@Tag(name = "入住管理", description = "入住相关接口")
@RestController
@RequestMapping("/checkin")
public class CheckinController {

    private static final Logger log = LoggerFactory.getLogger(CheckinController.class);

    @Autowired
    private ICheckinService checkinService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IRoomService roomService;
    
    @Autowired
    private IElderAssessmentService elderAssessmentService;

    /**
     * 获取今日入住人数
     * 统计elder_check_in表中status=4（已缴费入住）的今日记录数
     *
     * @return 今日入住人数
     */
    @Operation(summary = "获取今日入住人数", description = "统计elder_check_in表中status=4（已缴费入住）的今日记录数")
    @GetMapping("/todayCount")
    public RespObj<?> getTodayCheckedInCount() {
        // 获取今日开始和结束时间
        LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN); // 今日00:00:00
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);   // 今日23:59:59
        
        Long todayCount = checkinService.getTodayCheckedInCount(startTime, endTime);
        return new RespObj<Long>().success(todayCount);
    }

    /**
     * 获取待审核的入住记录数量
     * 统计elder_check_in表中status=1（待审核）的记录数
     *
     * @return 待审核的入住记录数量
     */
    @Operation(summary = "获取待审核的入住记录数量", description = "统计elder_check_in表中status=1（待审核）的记录数")
    @GetMapping("/pendingCount")
    public RespObj<?> getPendingReviewCount() {
        Long pendingCount = checkinService.getPendingReviewCount();
        return new RespObj<Long>().success(pendingCount);
    }

    /**
     * 获取可用房间数量
     * 统计elder_room表中status=1（可用）的记录数
     *
     * @return 可用房间数量
     */
    @Operation(summary = "获取可用房间数量", description = "统计elder_room表中status=1（可用）的记录数")
    @GetMapping("/availableRoomCount")
    public RespObj<?> getAvailableRoomCount() {
        Long availableCount = roomService.getAvailableRoomCount();
        return new RespObj<Long>().success(availableCount);
    }


    /**
     * 床位入住率查询
     */
    @Operation(summary = "入住率", description = "统计床位的可用的数量/总的数量")
    @GetMapping("/checkinRate")
    public RespObj<?> getCheckinCount() {
        Map<String,Object> availableCount = elderService.getBedOccupancyStatistics();
        return new RespObj<Map<String,Object>>().success(availableCount);
    }

    /**
     * 获取总的已入住人数
     */
    @Operation(summary = "总已入住人数", description = "统计elder_check_in表中status=4（已缴费入住）的总记录数")
    @GetMapping("/totalCheckedInCount")
    public RespObj<?> getTotalCheckedInCount() {
        log.info("开始获取总的已入住人数");
        Long count = checkinService.getTotalCheckedInCount();
        log.info("总的已入住人数：{}", count);
        return new RespObj<Long>().success(count);
    }

    /**
     * 获取未离开且指定状态的记录数
     * 
     * @param status 状态值(1-5)，如果为null则查询所有状态
     * @return 符合条件的记录数
     */
    @Operation(summary = "处理中人数统计", description = "统计elder_check_in表中is_leave=0且status在1-5之间的记录数")
    @GetMapping("/overall/process")
    public RespObj<?> getProcessingCount(@RequestParam(required = true) Integer status) {
        log.info("开始获取未离开且状态为{}的记录数", status != null ? status : "1-5");
        Map<String, Long> countMap = checkinService.getCountByStatus(status);
        log.info("未离开且状态为{}的记录数：{}", status != null ? status : "1-5", countMap);
        return new RespObj<Map<String, Long>>().success(countMap);
    }

    /**
     * 获取长者信息和入住状态列表，按入住时间倒序排列
     *
     * @return 长者状态信息列表
     */
    @Operation(summary = "长者状态列表", description = "关联查询长者信息和入住状态，按入住时间倒序排列")
    @GetMapping("/overall/recent")
    public RespObj<?> getElderStatusList() {
        log.info("开始获取长者状态列表");
        List<Map<String, Object>> elderStatusList = checkinService.getElderStatusList();
        log.info("获取到{}条长者状态记录", elderStatusList.size());
        return new RespObj<List<Map<String, Object>>>().success(elderStatusList);
    }
    
    /**
     * 获取长者评估详细信息
     *
     * @return 长者评估详细信息
     */
    @Operation(summary = "长者评估详细信息", description = "获取长者基本信息和评估详情")
    @GetMapping("/assessment/detail")
    public RespObj<?> getElderAssessmentDetail() {
        log.info("开始获取长者评估详细信息");
        ElderAssessmentVO elderAssessmentVO = elderAssessmentService.getElderAssessmentDetail();
        log.info("获取长者评估详细信息成功");
        return new RespObj<ElderAssessmentVO>().success(elderAssessmentVO);
    }

    /**
     * 更新入住记录状态
     *
     * @param id 入住记录ID
     * @param status 新状态值
     * @return 更新结果
     */
    @Operation(summary = "更新入住记录状态", description = "根据ID更新elder_check_in表中的status字段")
    @PostMapping("/updateStatus")
    public RespObj<?> updateCheckinStatus(
            @Parameter(description = "入住记录ID", required = true) @RequestParam Long id,
            @Parameter(description = "新状态值(1-5)", required = true) @RequestParam Integer status) {
        log.info("开始更新入住记录状态，ID：{}，新状态：{}", id, status);
        
        // 参数校验
        if (id == null || status == null || status < 1 || status > 5) {
            log.error("参数错误，ID：{}，状态：{}", id, status);
            return new RespObj<>().error("参数错误，状态值必须在1-5之间");
        }
        
        boolean result = checkinService.updateCheckinStatus(id, status);
        if (result) {
            log.info("更新入住记录状态成功，ID：{}，新状态：{}", id, status);
            return new RespObj<>().success("更新状态成功");
        } else {
            log.error("更新入住记录状态失败，ID：{}，新状态：{}", id, status);
            return new RespObj<>().error("更新状态失败");
        }
    }
    
    /**
     * 获取长者入住详情列表
     *
     * @return 长者入住详情列表
     */
    @Operation(summary = "长者入住详情列表", description = "获取长者入住详情，包含个人信息和入住信息")
    @GetMapping("/detail/list")
    public RespObj<?> getElderCheckinDetailList() {
        log.info("开始获取长者入住详情列表");
        List<ElderCheckinDetailVO> detailList = checkinService.getElderCheckinDetailList();
        log.info("获取到{}条长者入住详情记录", detailList.size());
        return new RespObj<List<ElderCheckinDetailVO>>().success(detailList);
    }
}
